<template>
  <button type="button" class="once-timing-click" @click="changeType" :disabled="disabled">
    {{text}}
  </button>
</template>

<script>
export default {
  name: 'OnceTimingClick',
  props: ['onText', 'offText', 'time'],
  data:()=>{
    return {
      text: '',
      type: 'on',
      disabled: false
    }
  },
  created() {
    this.text = this.onText
  },
  methods: {
    changeType() {
      this.$emit('timingRun')
      //其实可以不用判断，但是这样更加安全
      this.type = 'off'
      this.disabled = true // 控件无法再次做出响应
      this.timingRun(this[this.type + 'Text'], ()=>{
        this.type = 'on'
        this.disabled = false
        this.text = this[this.type + 'Text']
      })
    },
    //处理主要的时间控制逻辑
    timingRun(preffix, callback) {
      let time = this.time
      if(time <= 0) return
      this.text = preffix + ' ' + time
      const timer = setInterval(()=>{
        time--;
        //改变文字
        this.text = preffix + ' ' + time
        if(time <= 0){ // 时间到达时
          clearInterval(timer) //清除定时器
          callback && callback()
        } 
      }, 1000)
    }
  }
}
</script>

<style>
 .once-timing-click {
   color: #6a6a6a;
   background-color: transparent;
   border: none;
   padding: 0;
 }
</style>